package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class OrderTask {

    @Autowired
    OrderMapper orderMapper;


    @Scheduled(cron = "0 * * * * ?")//处理超时时间状态。每分钟触发一次。
//        @Scheduled(cron = "0/2 * * * * ?")
    //检测未付款的订单是否超过15min，如果超过15分钟，则会自动取消。
    public void processTimeOrder(){
        log.info("处理超时订单：{}", LocalDateTime.now());
        //查询未支付的超时订单并修改
       List<Orders>  ordersList = orderMapper.selectProcessTimeOrder(Orders.PENDING_PAYMENT,LocalDateTime.now().minusMinutes(15));
        if(ordersList != null && ordersList.size() > 0){
            ordersList.forEach(order -> {
                order.setStatus(Orders.CANCELLED);
                order.setCancelReason("支付超时，自动取消");
                order.setCancelTime(LocalDateTime.now());
                orderMapper.update(order);
            });
        }

    }

    /**
     * 处理“派送中”状态的订单
     */
    @Scheduled(cron = "0 0 1 * * ?")
    //将每天没有完成派送的订单自动完成。
//    @Scheduled(cron = "0/2 * * * * ?")
    public void processDeliveryOrder(){
        log.info("处理派送中订单：{}", new Date());
        // select * from orders where status = 4 and order_time < 当前时间-1小时
        //当前时间减去60分钟
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);
        List<Orders> ordersList = orderMapper.selectProcessTimeOrder(Orders.DELIVERY_IN_PROGRESS, time);

        if(ordersList != null && ordersList.size() > 0){

            ordersList.forEach(order -> {
                // 设置状态为：已完成并修改
                order.setStatus(Orders.COMPLETED);
                orderMapper.update(order);
            });
        }
    }

}
